const config = require('./config')
const request = require('./request')

//全局数据
const globalData = {
  lastLoginTargetUrl: '',  //最后一次登录成功后的目标路径
  sessionInfo: null,  //当前微信账号会话信息,包括:openid-用户唯一标识 session_key-会话密钥 unionid-用户在开放平台的唯一标识符
  userProfile: null,  //当前微信账号用户昵称头像信息,包括:avatarUrl city country gender(0-未知 1-男性 2-女性) language nickName province
  tokenInfo: null     //用户登录后的Token信息
}

//region User

/**
 * 获取当前小程序 appId
 * @return {string}
 */
function getAppId() {
  return wx.getAccountInfoSync().miniProgram.appId
}

/**
 * 获取用户信息。每次请求都会弹出授权窗口，用户同意后返回 userInfo。
 * @param desc {string} 声明获取用户个人信息后的用途，不超过30个字符
 */
function getUserProfile(desc) {
  if (globalData.userProfile) {
    return Promise.resolve(globalData.userProfile)
  }
  return new Promise((resolve, reject) => {
    wx.getUserProfile({
      lang: 'zh_CN',
      desc: desc,
      success(res) {
        globalData.userProfile = res.userInfo
        console.log(res.userInfo)
        resolve(res.userInfo)
      },
      fail(err) {
        reject(err)
        console.error('wx.getUserProfile fail', err)
      }
    })
  })
}

/**
 * 获取用户会话信息
 * @return {Promise<Object>}
 */
function getSessionInfo() {
  if (globalData.sessionInfo) {
    return Promise.resolve(globalData.sessionInfo)
  }

  return new Promise((resolve, reject) => {
    wx.login({
      success(res) {
        const code = res.code
        const appid = wx.getAccountInfoSync().miniProgram.appId
        request.post(config.code2SessionApiUrl, {appid, code}).then(r => {
          globalData.sessionInfo = r.data
          resolve(r.data)
        }).catch(e => {
          reject(e)
        })
      },
      fail(err) {
        console.error('wx.login fail', err)
      }
    })
  })
}

/**
 * 获取用户身份标识符(openid)
 * @return {Promise<String>}
 */
function getOpenid() {
  if (globalData.sessionInfo) {
    return Promise.resolve(globalData.sessionInfo.openid)
  }
  const openid = wx.getStorageSync('openid')
  if (openid) {
    return Promise.resolve(openid)
  }

  return new Promise((resolve, reject) => {
    getSessionInfo().then(res => {
      wx.setStorageSync('openid', res.openid)
      resolve(res.openid)
    }).catch(reject)
  })
}

/**
 * 获取用户会话key
 * @return {Promise<Object>}
 */
function getSessionKey() {
  if (globalData.sessionInfo) {
    return Promise.resolve(globalData.sessionInfo.sessionKey)
  }

  return new Promise((resolve, reject) => {
    getSessionInfo().then(res => {
      resolve(res.sessionKey)
    }).catch(reject)
  })
}

/**
 * 获取手机号码
 * @param encryptedData 包括敏感数据在内的完整用户信息的加密数据
 * @param iv 加密算法的初始向量
 * @return {Promise<Object>}
 */
function getPhoneNumber(encryptedData, iv) {
  return new Promise((resolve, reject) => {
    getSessionKey().then(res => {
      const sessionKey = res
      const appid = wx.getAccountInfoSync().miniProgram.appId
      request.post(config.phoneNumberApiUrl, {appid, sessionKey, encryptedData, iv}, {loading: '读取中...'}).then(r => {
        resolve(r.data)
      }).catch(reject)
    }).catch(reject)
  })
}

/**
 * 用户登录获取token,并把用户信息[userInfo]存入Storage中
 * @return {Promise<Object>}
 */
function login(data) {
  return new Promise((resolve, reject) => {
    request.post(config.loginApiUrl, data, {loading: '正在登录...'}).then(r => {
      const tokenInfo = r.data
      if (tokenInfo) {
        globalData.tokenInfo = tokenInfo
        wx.setStorageSync('tokenInfo', tokenInfo)
        resolve(tokenInfo)
      } else {
        resolve(null)
      }
    }).catch(reject)
  })
}

function logout() {
  globalData.lastLoginTargetUrl = null
  globalData.sessionInfo = null
  globalData.userProfile = null
  globalData.tokenInfo = null
  wx.removeStorageSync('tokenInfo')
  wx.removeStorageSync('openid')
}

/**
 * 获取用户Token信息
 * @return {Promise<Object>}
 */
function getTokenInfo() {
  if (globalData.tokenInfo) {
    return globalData.tokenInfo
  }
  return wx.getStorageSync('tokenInfo') || null
}

/**
 * 如果当前已登录成功返回true,否则返回false
 */
function isLogin() {
  if (globalData.tokenInfo) {
    return Promise.resolve(true)
  }
  const tokenInfo = wx.getStorageSync('tokenInfo')
  if (tokenInfo) {
    globalData.tokenInfo = tokenInfo
    return Promise.resolve(true)
  }
  return Promise.resolve(false)
}

function setLastLoginTargetUrl(targetUrl) {
  globalData.lastLoginTargetUrl = targetUrl
}

function getLastLoginTargetUrl() {
  return globalData.lastLoginTargetUrl
}

/**
 * 登录拦截器,如果当前未登录,则跳转到登录页面
 * @param targetUrl 登录成功后的目标地址
 * @return {Promise}
 */
function loginInterceptor(targetUrl) {
  return new Promise((resolve, reject) => {
    isLogin().then(r => {
      if (r === true) {
        resolve({})
      } else {
        globalData.lastLoginTargetUrl = targetUrl
        wx.redirectTo({
          url: config.loginPageUrl
        })
      }
    }).catch(reject)
  })
}


//endregion

module.exports = {
  login,
  logout,
  isLogin,
  loginInterceptor,
  getLastLoginTargetUrl,
  setLastLoginTargetUrl,
  getUserProfile,
  getSessionInfo,
  getTokenInfo,
  getAppId,
  getOpenid,
  getSessionKey,
  getPhoneNumber
}
